package mamikeji.liaowa.ui.fragment.main_date;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyForumBean;
import mamikeji.liaowa.bean.Web_Focus;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.MainActivity;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.activity.forum.ForumMSGActivity;
import mamikeji.liaowa.ui.adapter.Main_ForumAdapter;
import mamikeji.liaowa.ui.fragment.BaseFragment;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.main_view.PullLoadMoreRecyclerView;

/**
 * Created by 廉冲-android开发 on 2017/9/13.
 */
public class Main_ForumFragment extends BaseFragment {
    private static final String TAG = "Main_ForumFragment";
    private static final int TAG_FORUM = 1002;
    View mView;
    @BindView(R.id.pullLoadMoreRecyclerView_main_fragment_forum)
    PullLoadMoreRecyclerView pullLoadMoreRecyclerViewMainFragmentForum;
    @BindView(R.id.multiStateView_main_fragment_forum)
    MultiStateView multiStateViewMainFragmentForum;
    private RecyclerView mRecyclerView;

    /**
     * 请求的页数
     */
    private int page = 1;

    //宝妈圈适配器
    Main_ForumAdapter main_forumAdapter;
    //话题数据集
    private List<MyForumBean.DataEntity> dataEntityList = new ArrayList<>();
    //话题每页的活动数据集合
    ArrayList<MyForumBean.DataEntity> mList;

    private int list_item_num = -1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_main_forum, container, false);
        ButterKnife.bind(this, mView);

        init();
        return mView;
    }

    private void init() {
        multiStateViewMainFragmentForum.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getMain_ForumData(1, 10);
                    }
                });

        //获取首页朋友圈
        getMain_ForumData(1, 10);

        //获取mRecyclerView对象
        mRecyclerView = pullLoadMoreRecyclerViewMainFragmentForum.getRecyclerView();
        //代码设置scrollbar无效？未解决！
        mRecyclerView.setVerticalScrollBarEnabled(true);
//        设置下拉刷新是否可见
        pullLoadMoreRecyclerViewMainFragmentForum.setRefreshing(false);
//        设置是否可以下拉刷新
        pullLoadMoreRecyclerViewMainFragmentForum.setPullRefreshEnable(false);
        //设置是否可以上拉刷新
        pullLoadMoreRecyclerViewMainFragmentForum.setPushRefreshEnable(true);
        //显示下拉刷新
        pullLoadMoreRecyclerViewMainFragmentForum.setRefreshing(false);
        //设置上拉刷新文字
        pullLoadMoreRecyclerViewMainFragmentForum.setFooterViewText("正在加载···");
//        设置上拉刷新文字颜色
        pullLoadMoreRecyclerViewMainFragmentForum.setFooterViewTextColor(R.color.color_app);
        //设置加载更多背景色
//        pullLoadMoreRecyclerViewMainFragmentForum.setFooterViewBackgroundColor(R.color.color_app);
        pullLoadMoreRecyclerViewMainFragmentForum.setLinearLayout();

        main_forumAdapter = new Main_ForumAdapter(getActivity(), dataEntityList);
        pullLoadMoreRecyclerViewMainFragmentForum.setAdapter(main_forumAdapter);

        pullLoadMoreRecyclerViewMainFragmentForum.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                getMain_ForumData(++page, 10);
            }
        });

        main_forumAdapter.setItemClickListener(new Main_ForumAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (getJudgeLogin()){
                    list_item_num = position;
                    int num = dataEntityList.get(position).getBrowse_total();
                    dataEntityList.get(position).setBrowse_total(num++);
                    main_forumAdapter.notifyDataSetChanged();

                    Intent intent = new Intent(getActivity(), ForumMSGActivity.class);
                    intent.putExtra("MyForumBean", dataEntityList.get(position));
                    startActivityForResult(intent, TAG_FORUM);
                }
            }

            @Override
            public void onZanClick(int position) {
                if (getJudgeLogin()){
                    getFabulousCircle(position);
                }
            }

            @Override
            public void onGuanZhuClick(int position) {
                MobclickAgent.onEvent(getContext(),"HotTopicPayAttentionTo");//热门话题-关注
                if (getJudgeLogin()){
                    getGuanZhuCircle(position);
                }
            }

            @Override
            public void onMSGClick(int position) {
                Intent mIntent = new Intent(getActivity(), FriendMSGActivity.class);
                mIntent.putExtra(HttpKey.Friend_MSG_friendcode, dataEntityList.get(position).getUsercode());
                startActivityForResult(mIntent, TAG_FORUM);
            }
        });
    }

    /**
     * 获取首页朋友圈数据
     *
     * @param indexpage
     * @param pagesize
     * @return
     */
    public void getMain_ForumData(int indexpage, int pagesize) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_list_current, indexpage + "");
        formMap.put(HttpKey.Forum_list_pagesize, pagesize + "");
        formMap.put(HttpKey.Forum_list_topic_id, "1");
        formMap.put(HttpKey.Forum_list_usercode, ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null ? "1" : ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.GetTopicPage, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMain_ForumData", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MyForumBean bean = new Gson().fromJson(response, MyForumBean.class);

                        mList = (ArrayList<MyForumBean.DataEntity>) bean.getData();

                        if (mList != null && mList.size() > 0) {
                            if (page == 1) {
                                dataEntityList.clear();
                                dataEntityList.addAll(mList);
                                //刷新数据
                                main_forumAdapter.addAllData(dataEntityList);
                                pullLoadMoreRecyclerViewMainFragmentForum.setPullLoadMoreCompleted();
                            } else {
                                //加载更多
                                dataEntityList.addAll(mList);
                                main_forumAdapter.addAllData(dataEntityList);
                                pullLoadMoreRecyclerViewMainFragmentForum.setPullLoadMoreCompleted();
                            }

                            multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (page == 1) {
                                multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            } else {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        ForToast.showToast(R.string.error_down_end);
                                        //刷新数据
                                        main_forumAdapter.notifyDataSetChanged();
                                        pullLoadMoreRecyclerViewMainFragmentForum.setPullLoadMoreCompleted();
                                    }
                                }, 1000);
                                multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }
                        }
                    } else {
                        multiStateViewMainFragmentForum.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousCircle(final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_Praise_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Forum_Praise_topic_id, dataEntityList.get(position).getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicPraise, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int num = dataEntityList.get(position).getPraise_total();
                        if (dataEntityList.get(position).getIs_praise() == 1) {
                            dataEntityList.get(position).setIs_praise(0);
                            dataEntityList.get(position).setPraise_total(--num);
                        } else {
                            dataEntityList.get(position).setIs_praise(1);
                            dataEntityList.get(position).setPraise_total(++num);
                        }
                        main_forumAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 关注朋友
     */
    public void getGuanZhuCircle(final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Follow_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Follow_followusercode, dataEntityList.get(position).getUsercode());
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MSG_follow, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int date = Integer.parseInt(jsonObject.getString("data"));
                        for (int i = 0; i < dataEntityList.size(); i++) {
                            if (dataEntityList.get(i).getUsercode().equals(dataEntityList.get(position).getUsercode())) {
                                dataEntityList.get(i).setIs_follow(date);
                            }
                        }

                        Web_forum_changeBean web_forum_changeBean = new Web_forum_changeBean(0,0,0,new ArrayList<Web_Focus>() , 0);

                        int follow = ForPreference.getInt(ForContents.USER_follow);//关注数
                        switch (date) {
                            case 1:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(1,dataEntityList.get(position).getUsercode()));
                                break;
                            case 2:
                                ForPreference.putInt(ForContents.USER_follow, --follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(2,dataEntityList.get(position).getUsercode()));
                                break;
                            case 3:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(3,dataEntityList.get(position).getUsercode()));
                                break;
                        }

                        ((MainActivity) getActivity()).getMainFragmentRefreshGuanzhu(true , web_forum_changeBean);
                        ((MainActivity) getActivity()).textViewRightFollow.setText(ForPreference.getInt(ForContents.USER_follow) + "");//设置关注数量
                        main_forumAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == TAG_FORUM) {
                ForLog.i(TAG,"1");
                Web_forum_changeBean web_forum_changeBean = (Web_forum_changeBean) data.getSerializableExtra("web_forum_changeBean");

                dataEntityList.get(list_item_num).setIs_praise(web_forum_changeBean.getZanStatic());
                dataEntityList.get(list_item_num).setPraise_total(web_forum_changeBean.getZanNum());
                dataEntityList.get(list_item_num).setMessage_total(web_forum_changeBean.getCommentNum());
                dataEntityList.get(list_item_num).setIs_collection(web_forum_changeBean.getIsCollection());

                if (web_forum_changeBean.getWebFocusList() != null){
                    if (web_forum_changeBean.getWebFocusList().size() > 0) {
                        for (int i = 0; i < web_forum_changeBean.getWebFocusList().size(); i++) {
                            for (int j = 0; j < dataEntityList.size(); j++) {
                                if (web_forum_changeBean.getWebFocusList().get(i).getFollowusercode().
                                        equals(dataEntityList.get(j).getUsercode())) {
                                    dataEntityList.get(j).setIs_follow(web_forum_changeBean.getWebFocusList().get(i).getFocusNum());
                                }
                            }
                        }
                    }
                }

                main_forumAdapter.notifyDataSetChanged();
            }
        }
    }

    public void getRefreshDate(Web_forum_changeBean web_forum_changeBean){
        if (web_forum_changeBean.getWebFocusList() != null){
            if (web_forum_changeBean.getWebFocusList().size() > 0) {
                for (int i = 0; i < web_forum_changeBean.getWebFocusList().size(); i++) {
                    for (int j = 0; j < dataEntityList.size(); j++) {
                        if (web_forum_changeBean.getWebFocusList().get(i).getFollowusercode().
                                equals(dataEntityList.get(j).getUsercode())) {
                            dataEntityList.get(j).setIs_follow(web_forum_changeBean.getWebFocusList().get(i).getFocusNum());
                        }
                    }
                }
            }
        }

        main_forumAdapter.notifyDataSetChanged();
    }
}
